#include <myheader_c_plus.h>
using std::endl;
using std::cout;
using std::istream;
using std::ostream;
using std::string;
using std::cin;
class  CharArray{
private:
    char *_pchar;
    size_t _size;
public:
    CharArray(const char * str)
    :_pchar(new char [strlen(str) + 1]())
    ,_size(strlen(str) + 1)
    {
        strcpy(_pchar,str);
    }

    ~CharArray(){
        if(_pchar){
            delete [] _pchar;
            _pchar =nullptr;
        }
    }

    //[]运算符重载,不能友元函数，因为调用者是this
    char & operator[](size_t index){
        if(index < (this->_size - 1)){
            return this->_pchar[index];
        }else{
            cout << "out of range" << endl;
            static char ch = '\0';
            return ch;
        }

    }
friend istream & operator>>(istream & is, CharArray & rhs);
friend ostream & operator<<(ostream & os, CharArray & rhs);
};
//输入流 >> 运算符重载，用友元函数
istream & operator>>(istream & is, CharArray & rhs){
    string str;
    getline(is, str);
    if(rhs._pchar != nullptr){
        delete [] rhs._pchar;
        rhs._pchar = new char [str.length() + 1]();
        strcpy(rhs._pchar,str.c_str());
        rhs._size = str.length() + 1;
    }
    return is;

}

//输出流 << 运算符重载，用友元函数
ostream & operator<<(ostream & os, CharArray & rhs){
    if(rhs._pchar != nullptr){
        os << rhs._pchar;
    }
    return os;
}

int main(int argc, char *argv[])
{
    CharArray  exp("hello");

    cout << exp[0];

    cin >> exp;
    cout << exp;
    return 0;
}

